// 统一处理登录过期：不再前端强制超时，转由后台控制
class SessionTimeoutManager {
    constructor(options = {}) {
        this.options = Object.assign({
            alertId: 'login-session-alert',
            loginModalId: 'login',
            defaultMessage: '登录状态已过期，请重新登录。'
        }, options);

        this.registerAjaxHandlers();
        this.registerModalReset();
    }

    registerAjaxHandlers() {
        if (!window.jQuery) {
            return;
        }

        $(document).ajaxError((event, jqXHR) => {
            if (jqXHR.status === 401) {
                let message = this.options.defaultMessage;
                if (jqXHR.responseJSON) {
                    message = jqXHR.responseJSON.error || jqXHR.responseJSON.message || message;
                }
                this.showLoginModal(message);
            }
        });
    }

    registerModalReset() {
        if (!window.jQuery) {
            return;
        }

        const selector = `#${this.options.loginModalId}`;
        $(document).on('hidden.bs.modal', selector, () => this.hideAlert());
    }

    showLoginModal(message) {
        const alertBox = document.getElementById(this.options.alertId);
        if (alertBox) {
            alertBox.textContent = message || this.options.defaultMessage;
            alertBox.classList.remove('d-none');
        }

        if (window.jQuery) {
            const modal = $(`#${this.options.loginModalId}`);
            if (modal.length) {
                modal.modal('show');
                return;
            }
        }

        // 回退：无模态框时使用 alert，并跳转登录页
        window.alert(message || this.options.defaultMessage);
        window.location.href = '/login';
    }

    hideAlert() {
        const alertBox = document.getElementById(this.options.alertId);
        if (alertBox) {
            alertBox.classList.add('d-none');
            alertBox.textContent = '';
        }
    }
}

window.sessionManager = new SessionTimeoutManager();
window.handleAuthExpired = (message) => window.sessionManager.showLoginModal(message);
